package com.example.utils;

import org.apache.commons.cli.*;

import java.io.File;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;

public class Utils {

    public static Optional<String[]> RegularExpressionGroups(String input, String pattern) {
        Pattern compiledPattern = Pattern.compile(pattern);
        Matcher matcher = compiledPattern.matcher(input);
        if (matcher.matches()) {
            return Optional.of(IntStream.rangeClosed(0, matcher.groupCount())
                    .mapToObj(matcher::group)
                    .toArray(String[]::new));
        }
        return Optional.empty();
    }

    public static boolean isMatch(String input, String pattern) {
        Pattern compiledPattern = Pattern.compile(pattern);
        Matcher matcher = compiledPattern.matcher(input);
        return matcher.matches();
    }

    public static CommandLine parseCommandLineArgs(String[] args) throws ParseException {
        Options options = new Options();

        Option input = new Option("i", "input", true, "input directory path");
        input.setRequired(false);
        options.addOption(input);

        Option output = new Option("o", "output", true, "output directory path");
        output.setRequired(false);
        options.addOption(output);

        CommandLineParser parser = new DefaultParser();

        try {
            return parser.parse(options, args);
        } catch (ParseException e) {
            System.err.println(e.getMessage());
            throw e;
        }
    }

    public static boolean checkDirectoryExists(String directoryPath, String directoryType) {
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            System.err.println(directoryType + " directory does not exist: " + directoryPath);
            System.err.println("Please create the directory and try again.");
            return false;
        }
        return true;
    }
}
